/**
 * Canvas loading indicator
 * @author Levin
 * @version 1.0
 */
JF.M("Loader",(function($){
	var p={},pub={};
	p.spinner=function(height, con){
		this.height=height||32;
		this.width =(con != null)?(this.height+82): this.height;
		
		this.obj = document.createElement("canvas");
		this.obj.setAttribute("width", this.width);
		this.obj.setAttribute("height", this.height);
		this.ctx = this.obj.getContext("2d");
		// RGB
		this.color = [51, 51, 51];

		this.ctx.save();
		this._initText();

		this.ctx.restore();
		// 记录转动的度数,分8步
		this.rotation=0;
		this.running=null;//计时器
	};

	// 每隔125ms会调用一次,绘制一个loading圆
	p.spinner.prototype={
		draw : function(){
			var h = this.height, ctx = this.ctx, c = h / 16, d = h / 5, degree = -Math.PI * 2 / 10;
			ctx.save();
			// clearRect(x,y,width,height) : Clears the specified area and makes it fully transparent
			ctx.clearRect(0, 0, h, h);
			// 移到中点
			ctx.translate(h / 2, h / 2);
			// 把一个圆分成8段,分别绘制
			for (var i = 0; i < 10; i++) {
				ctx.save();
				// 旋转一段的度数
				ctx.rotate(i * degree); 
				// 根据旋转的角度设置颜色与透明度,eg:
				// rotation=0 的时候, alpha的值 1, 0.875 ... 0.125
				// rotation=1 的时候, alpha的值 0.875, 0.75 ... 1
				ctx.fillStyle = "rgba(" + this.color[0] + "," + this.color[1] + "," + this.color[2] + "," + (10 - (i + this.rotation) % 10) / 10 + ")";
				// 绘制 fillRect(x,y,width,height) : Draws a filled rectangle
				ctx.fillRect(-c / 2, d, c, d);
				ctx.restore();
			}
			ctx.restore();
			this.rotation++;
			this.rotation %= 10;

		},//draw
		start:function(){
			var me=this;
			// 由于分成10段,所以时间为100ms
			this.running=window.setInterval(function(){me.draw();}, 100); 
			me.draw();
		},
		stop:function(){
			window.clearInterval(this.running);
			this.running=null;
		},//stop
		_initText:function(txt){
			if(!txt){
				return;
			}
			var fsize =((this.height>24)?16:14) + "px";
			this.ctx.fillStyle = "#646464";
			this.ctx.font = fsize+" \"Microsoft YaHei\",Helvetica";
			this.ctx.textBaseline = "middle";
			this.ctx.fillText(txt, this.height+5, this.height/2);
		}//_initText
	};//p.spinner.prototype


	pub.Attach=function($t,opts){
		opts=$.extend({
			con:null,
			autoStart:false
		},opts||{});

		var canvas=null;
		if(!(canvas=$t.data("spinner")) ){
			// 创建 Canvas
			canvas = new p.spinner(opts.height, opts.con);
			canvas.obj.id = "sp";

			$t.prepend(canvas.obj);
			if(opts.autoRun){
				canvas.start();
			}

			$t.data("spinner",canvas);
			return canvas;
		};

		if(opts.autoRun){
			canvas.start();
		}

		return canvas;

	};
	pub.Detach=function($t,forever){
		var canvas=null;
		if(!(canvas=$t.data("spinner")) ){
			return;
		}
		forever=forever||false;

		canvas.stop();
		if(forever){
			$t.find("#sp").remove();
		}


	};

	return pub;

})(jQuery));